﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainPresenter.cs" company="SMART business">
//   Copyright (c) 2014 All Rights Reserved
// </copyright>
// <summary>
//   The interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using McTools.Xrm.Connection;
using Microsoft.Xrm.Sdk;
using UsersSettingsTool.Additional_Classes.Classes;
using UsersSettingsTool.Additional_Classes.MessageService;
using UsersSettingsTool.Additional_Classes.TraceService;
using UsersSettingsTool.Models.Interfaces;
using UsersSettingsTool.Options;
using UsersSettingsTool.Views;

namespace UsersSettingsTool.Core
{
    internal class MainPresenter
    {
        private readonly IMainView _mainView;

        private readonly IXrm _xrm;

        private readonly IMessageService _messageService;

        private readonly ITraceService _traceService;

        private List<CrmUser> SystemUsers { get; set; }

        private List<Currency> Currencies { get; set; }

        // private List<Format> Formats { get; set; }

        private List<RecordPerPage> RecordsPerPage { get; set; }

        private List<Tab> Tabs { get; set; }

        private List<object> TrackValues { get; set; }

        private List<object> CreateFromEmailOptions { get; set; }

        private List<Pane> Panes { get; set; }

        private List<TimeZones> TimeZones { get; set; }

        private List<CalendarList> CalendarLists { get; set; }

        private List<object> TimesList { get; set; }

        private List<object> InstalledLanguages { get; set; }

        public MainPresenter(IMainView mainView, IXrm xrm, IMessageService messageService, ITraceService traceService)
        {
            _mainView = mainView;
            _xrm = xrm;
            _messageService = messageService;
            _traceService = traceService;

            mainView.ConnectionManagerConnectionFailed += ManagerConnectionFailed;
            mainView.ConnectionManagerConnectionSucceed += ManagerConnectionSucceed;
            mainView.ConnectionManagerStepChanged += ManagerStepChanged;

            mainView.GetUsers += GetUsers;

            // mainView.GetTabs += LoadTab;
            mainView.ShowUserInfo += ShowUserInfo;
            mainView.ShowUserMailBox += ShowUserMailBox;
            mainView.ViewYourPrivacyStatement += ViewYourPrivacyStatement;

            mainView.UsersSelect += UsersSelect;

            mainView.SaveChanges += SaveChanges;
        }

        private void SaveChanges(object sender, EventArgs e)
        {
            try
            {
                var usersToSave = ((CustomEventArgs)e).List;

                var crmUser = new CrmUser
                                  {
                                      RecordsPerPage = new RecordPerPage(string.Empty, _mainView.GetRecordsPerPage()),
                                      Pane = new Pane(string.Empty, _mainView.GetPane()),
                                      Tab = new Tab(string.Empty, _mainView.GetTab()),
                                      AdvFindMode = _mainView.GetAdvFindMode(),
                                      TimeZone = new TimeZones(string.Empty, _mainView.GetTimeZone()),
                                      Currency = new Currency(string.Empty, _mainView.GetCurrency()),
                                      IsEnableHighContrast = _mainView.GetIsEnabledHighContrast(),
                                      IsEnableCountryRegionCodePrefixing = _mainView.GetEnableCountryRegionCodePrefixing(),
                                      CountryCode = _mainView.GetCountryCode(),
                                      CalendarView = _mainView.GetCalendarView(),
                                      WorkDayStartTime = _mainView.GetWorkDayStartTime(),
                                      WorkDayStopTime = _mainView.GetWorkDayStopTime(),
                                      IsSendAsAllowed = _mainView.GetIsSendAsAllowed(),
                                      IncomingEmailFilteringMethod = _mainView.GetIncomingEmailFilteringMethod(),
                                      AutoCreateContactOnPromote = _mainView.GetIsAutoCreateContactOnPromote(),
                                      ReportScriptErrors = _mainView.GetSetReportScriptErrors(),
                                      HelpLanguage = _mainView.GetHelpLanguage(),
                                      UiLanguage = _mainView.GetUiLanguage()
                                  };

                foreach (Guid item in usersToSave)
                {
                    var user = _xrm.GetUser(item);

                    user = UsersDiff(user, crmUser);
                    user.Id = item;

                    _xrm.UpdateSystemUser(user);
                }

                GetUsers(null, EventArgs.Empty);
                _messageService.ShowMessage("Ok!");
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private static CrmUser UsersDiff(CrmUser settingsUser, CrmUser currentUser)
        {
            var user = new CrmUser();

            if (settingsUser.AdvFindMode != currentUser.AdvFindMode)
                user.Attributes.Add("advancedfindstartupmode", currentUser.AdvFindMode);

            if (settingsUser.Currency.Value != currentUser.Currency.Value)
            {
                user.Attributes.Add("transactioncurrencyid",
                    currentUser.Currency.Value != new Guid()
                        ? new EntityReference("transactioncurrency", currentUser.Currency.Value)
                        : null);
            }
            if (settingsUser.UiLanguage != currentUser.UiLanguage && currentUser.UiLanguage != -1)
                user.Attributes.Add("uilanguageid", currentUser.UiLanguage);

            if (settingsUser.ReportScriptErrors != currentUser.ReportScriptErrors)
                user.Attributes.Add("reportscripterrors", new OptionSetValue(currentUser.ReportScriptErrors));

            if (settingsUser.AutoCreateContactOnPromote != currentUser.AutoCreateContactOnPromote)
                user.Attributes.Add("autocreatecontactonpromote", currentUser.AutoCreateContactOnPromote);

            if (settingsUser.CalendarView != currentUser.CalendarView && currentUser.CalendarView != -1)
                user.Attributes.Add("defaultcalendarview", currentUser.CalendarView);

            if (settingsUser.CountryCode != currentUser.CountryCode)
                user.Attributes.Add("defaultcountrycode", currentUser.CountryCode);

            if (settingsUser.Pane.Value != currentUser.Pane.Value)
                user.Attributes.Add("homepagearea", currentUser.Pane.Value);

            if (settingsUser.Tab.Value != currentUser.Tab.Value && !string.IsNullOrWhiteSpace(currentUser.Tab.Value))
                user.Attributes.Add("homepagesubarea", currentUser.Tab.Value);

            if (settingsUser.IsEnableCountryRegionCodePrefixing != currentUser.IsEnableCountryRegionCodePrefixing)
                user.Attributes.Add("isdefaultcountrycodecheckenabled", currentUser.IsEnableCountryRegionCodePrefixing);

            if (settingsUser.IsEnableHighContrast != currentUser.IsEnableHighContrast)
                user.Attributes.Add("useimagestrips", currentUser.IsEnableHighContrast);

            if (settingsUser.HelpLanguage != currentUser.HelpLanguage && currentUser.HelpLanguage != -1)
                user.Attributes.Add("helplanguageid", currentUser.HelpLanguage);

            if (settingsUser.IsSendAsAllowed != currentUser.IsSendAsAllowed)
                user.Attributes.Add("issendasallowed", currentUser.IsSendAsAllowed);

            if (settingsUser.WorkDayStartTime != currentUser.WorkDayStartTime)
                user.Attributes.Add("workdaystarttime", currentUser.WorkDayStartTime);

            if (settingsUser.RecordsPerPage.Value != currentUser.RecordsPerPage.Value)
                user.Attributes.Add("paginglimit", currentUser.RecordsPerPage.Value);

            if (settingsUser.WorkDayStopTime != currentUser.WorkDayStopTime)
                user.Attributes.Add("workdaystoptime", currentUser.WorkDayStopTime);

            if (settingsUser.IncomingEmailFilteringMethod != currentUser.IncomingEmailFilteringMethod)
                user.Attributes.Add("incomingemailfilteringmethod", new OptionSetValue(currentUser.IncomingEmailFilteringMethod));

            if (settingsUser.TimeZone.Value != currentUser.TimeZone.Value && currentUser.TimeZone.Value != -1)
                user.Attributes.Add("timezonecode", currentUser.TimeZone.Value);

            return user;
        }

        private void ViewYourPrivacyStatement(object sender, EventArgs e)
        {
            try
            {
                Process.Start(@"http://windows.microsoft.com/uk-UA/Windows/microsoft-error-reporting-privacy-statement");
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void ShowUserInfo(object sender, EventArgs e)
        {
            try
            {
                var serverUrl = _xrm.GetOrganizationUrl();
                var userId = _xrm.GetCurrentUserId();

                Process.Start(serverUrl + @"/main.aspx?etn=systemuser&pagetype=entityrecord&id=" + userId);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void ShowUserMailBox(object sender, EventArgs e)
        {
            try
            {
                var serverUrl = _xrm.GetOrganizationUrl();
                var userId = _xrm.GetCurrentUserId();
                var mailBoxId = _xrm.GetMailBox(userId);

                Process.Start(serverUrl + @"/main.aspx?etc=9606&extraqs=?etc=9606&id=" + mailBoxId.Id + @"&histKey=47698884&newWindow=true&pagetype=entityrecord#515135509");
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void UsersSelect(object sender, EventArgs e)
        {
            var users = ((CustomEventArgs)e).List;

            var panesList = new List<string>();
            var tabsList = new List<string>();
            var recordsPerPage = new List<int>();
            var timeZones = new List<int>();
            var advancedFindModes = new List<object>();
            var currencies = new List<Guid>();
            var autoCreateContactOnPromoteList = new List<int>();
            var reportScriptErrorsList = new List<int>();
            var helpLanguages = new List<int>();
            var uiLanguages = new List<int>();
            var countryCodesList = new List<string>();
            var calendarViewsList = new List<int>();
            var workDayStartTimes = new List<string>();
            var workDayStopTimes = new List<string>();
            var incomingEmailFilteringMethods = new List<int>();
            var isSendAsAllowedList = new List<bool>();
            var enableHighContrasts = new List<bool>();
            var enableCountryRegionCodePrefixingList = new List<bool>();

            foreach (var userId in users)
            {
                var user = _xrm.GetUser((Guid)userId);

                if (user != null)
                {
                    recordsPerPage.Add(user.RecordsPerPage.Value);
                    timeZones.Add(user.TimeZone.Value);
                    advancedFindModes.Add(user.AdvFindMode);
                    enableHighContrasts.Add(user.IsEnableHighContrast);
                    enableCountryRegionCodePrefixingList.Add(user.IsEnableCountryRegionCodePrefixing);
                    countryCodesList.Add(user.CountryCode);
                    currencies.Add(user.Currency.Value);
                    calendarViewsList.Add(user.CalendarView);
                    workDayStartTimes.Add(user.WorkDayStartTime);
                    workDayStopTimes.Add(user.WorkDayStopTime);
                    incomingEmailFilteringMethods.Add(user.IncomingEmailFilteringMethod);
                    isSendAsAllowedList.Add(user.IsSendAsAllowed);
                    autoCreateContactOnPromoteList.Add(user.AutoCreateContactOnPromote);
                    reportScriptErrorsList.Add(user.ReportScriptErrors);
                    helpLanguages.Add(user.HelpLanguage);
                    uiLanguages.Add(user.UiLanguage);

                    if (user.Pane.Value != null)
                    {
                        panesList.Add(user.Pane.Value);
                    }

                    if (user.Tab.Text != null)
                    {
                        tabsList.Add(user.Tab.Value);
                    }
                }
            }

            recordsPerPage = recordsPerPage.Distinct().ToList();
            panesList = panesList.Distinct().ToList();
            timeZones = timeZones.Distinct().ToList();
            advancedFindModes = advancedFindModes.Distinct().ToList();
            currencies = currencies.Distinct().ToList();
            enableHighContrasts = enableHighContrasts.Distinct().ToList();
            countryCodesList = countryCodesList.Distinct().ToList();
            calendarViewsList = calendarViewsList.Distinct().ToList();
            workDayStopTimes = workDayStopTimes.Distinct().ToList();
            workDayStartTimes = workDayStartTimes.Distinct().ToList();
            incomingEmailFilteringMethods = incomingEmailFilteringMethods.Distinct().ToList();
            isSendAsAllowedList = isSendAsAllowedList.Distinct().ToList();
            autoCreateContactOnPromoteList = autoCreateContactOnPromoteList.Distinct().ToList();
            reportScriptErrorsList = reportScriptErrorsList.Distinct().ToList();
            helpLanguages = helpLanguages.Distinct().ToList();
            uiLanguages = uiLanguages.Distinct().ToList();

            var panes = panesList.Count.Equals(1)
                ? (from Pane pane in Panes where pane.Value == panesList[0] select pane.Text).First()
                : Panes[0].Text;

            var tabs = tabsList.Count.Equals(1)
                ? (from Tab tab in Tabs where tab.Value == tabsList[0] select tab.Text).First()
                : Tabs[0].Text;

            var records = recordsPerPage.Count.Equals(1)
                ? (from RecordPerPage record in RecordsPerPage where record.Value == recordsPerPage[0] select record.Text).FirstOrDefault()
                : RecordsPerPage[0].Text;

            var timeZone = timeZones.Count.Equals(1)
                ? (from TimeZones record in TimeZones where record.Value == timeZones[0] select record.Text).FirstOrDefault()
                : TimeZones[0].Text;

            var calendarView = calendarViewsList.Count.Equals(1)
                ? (from dynamic record in CalendarLists where record.Value == calendarViewsList[0] select record.Text).FirstOrDefault()
                : "Default";

            var workDayStartTime = workDayStartTimes.Count.Equals(1)
                ? (from dynamic record in TimesList where record.Value == workDayStartTimes[0] select record.Text).FirstOrDefault()
                : "Default";

            var workDayStopTime = workDayStopTimes.Count.Equals(1)
                ? (from dynamic record in TimesList where record.Value == workDayStopTimes[0] select record.Text).FirstOrDefault()
                : "Default";

            var incomingEmailFilteringMethod = incomingEmailFilteringMethods.Count.Equals(1)
                ? (from dynamic record in TrackValues where record.Value == incomingEmailFilteringMethods[0] select record.Text).FirstOrDefault()
                : "Default";

            var autoCreateContactOnPromote = autoCreateContactOnPromoteList.Count.Equals(1)
                ? (from dynamic record in CreateFromEmailOptions where record.Value == autoCreateContactOnPromoteList[0] select record.Text).FirstOrDefault()
                : "Default";

            var helpLanguage = helpLanguages.Count.Equals(1)
                ? (from dynamic record in InstalledLanguages where record.Value.ToString() == helpLanguages[0].ToString() select record.Text).FirstOrDefault()
                : "Default";

            var uiLanguage = uiLanguages.Count.Equals(1)
                ? (from dynamic record in InstalledLanguages where record.Value.ToString() == uiLanguages[0].ToString() select record.Text).FirstOrDefault()
                : "Default";

            var reportScriptErrors = reportScriptErrorsList.Count.Equals(1) ? reportScriptErrorsList[0] : 1;

            var isAutoCreate = !autoCreateContactOnPromote.Equals("Default");

            var countryCode = countryCodesList.Count.Equals(1) ? countryCodesList[0] : string.Empty;

            var enableHighContrast = enableHighContrasts.Count.Equals(1) && enableHighContrasts[0];

            var isSendAsAllowed = isSendAsAllowedList.Count.Equals(1) && isSendAsAllowedList[0];

            var enableCountryRegionCodePrefixing = enableCountryRegionCodePrefixingList.Count.Equals(1) && enableCountryRegionCodePrefixingList[0];

            var currency = "Empty";
            if (currencies.Count.Equals(1))
            {
                var val = currencies[0];
                currency = (
                            from Currency record in Currencies
                            where record.Value == val
                            select record.Text
                           ).FirstOrDefault();
            }

            var advFindMode = advancedFindModes.Count.Equals(1) ? advancedFindModes[0].ToString() : "1";

            _mainView.SetPane(panes);
            _mainView.SetTab(tabs);
            _mainView.SetRecordPerPage(records);
            _mainView.SetTimeZone(timeZone);
            _mainView.SetAdvancedFindMode(advFindMode);
            _mainView.SetCurrency(currency);
            _mainView.SetHighContrast(enableHighContrast);
            _mainView.SetCountryRegionCodePrefixing(enableCountryRegionCodePrefixing);
            _mainView.SetCountryCode(countryCode);
            _mainView.SetCalendarView(calendarView);
            _mainView.SetWorkDayStartTime(workDayStartTime);
            _mainView.SetWorkDayStopTime(workDayStopTime);
            _mainView.SetSendAsAllowed(isSendAsAllowed);
            _mainView.SetTrackValues((string)incomingEmailFilteringMethod);
            _mainView.SetAutoCreateEntity(autoCreateContactOnPromote);
            _mainView.SetAutoCreateOption(isAutoCreate);
            _mainView.SetReportScriptErrors(reportScriptErrors);
            _mainView.SetHelpLanguage(helpLanguage);
            _mainView.SetUiLanguage(uiLanguage);
        }

        private void ClearUserList()
        {
            _mainView.SetUserList(new List<CrmUser>());
        }

        private void SetDefaultValues()
        {
            ClearUserList();

            var progress = 1;

            _mainView.SetProgress(++progress);
            LoadPanes();
            _mainView.SetProgress(++progress);
            LoadTabs();
            _mainView.SetProgress(++progress);
            LoadRecordsPerPage();
            _mainView.SetProgress(++progress);
            LoadTimeZones();
            _mainView.SetProgress(++progress);
            LoadCurrencies();
            _mainView.SetProgress(++progress);
            LoadCalendarList();
            _mainView.SetProgress(++progress);
            LoadTimesList();
            _mainView.SetProgress(++progress);
            LoadBaseLanguages();
            _mainView.SetProgress(++progress);
            LoadInstalledLanguages();
            _mainView.SetProgress(++progress);
            LoadTackValues();
            _mainView.SetProgress(++progress);
            LoadCreateFromEmailOptions();
            _mainView.SetProgress(++progress);
            //LoadFormats();
            _mainView.SetProgress(++progress);

            _messageService.ShowMessage("Done.");
        }

        //private void LoadFormats()
        //{
        //    try
        //    {
        //        Formats = _xrm.GetFormats();

        //        _mainView.SetFormats(Formats);
        //    }
        //    catch (Exception ex)
        //    {
        //        if (Debugger.IsAttached)
        //        {
        //            Debugger.Break();
        //        }

        //        _messageService.ShowError(ex.Message);
        //        _traceService.WriteError(ex);
        //    }
        //}

        private void LoadCreateFromEmailOptions()
        {
            try
            {
                CreateFromEmailOptions = _xrm.GetCreateFromEmailOptions();

                _mainView.SetCreateFromEmailOptions(CreateFromEmailOptions);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadTackValues()
        {
            try
            {
                TrackValues = _xrm.GetTrackValues();

                _mainView.SetTrackValues(TrackValues);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadRecordsPerPage()
        {
            try
            {
                RecordsPerPage = _xrm.GetRecordsPerPage();

                _mainView.FillRecordsPerPage(RecordsPerPage);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadInstalledLanguages()
        {
            try
            {
                InstalledLanguages = _xrm.GetInstalledLanguages();

                _mainView.FillLanguages(InstalledLanguages);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadBaseLanguages()
        {
            try
            {
                var baseLanguage = _xrm.GetBaseLanguage();

                _mainView.FillBaseLanguage(baseLanguage);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadTabs()
        {
            try
            {
                Tabs = _xrm.GetTabs();

                _mainView.FillTabs(Tabs);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadPanes()
        {
            try
            {
                Panes = _xrm.GetPanes();

                _mainView.FillPanes(Panes);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadCurrencies()
        {
            try
            {
                Currencies = _xrm.GetCurrencies();

                _mainView.FillCurrencies(Currencies);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadTimeZones()
        {
            try
            {
                TimeZones = _xrm.GetTimeZones();

                _mainView.FillTimeZones(TimeZones);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadCalendarList()
        {
            try
            {
                CalendarLists = _xrm.GetCalenderList();

                if (CalendarLists != null)
                {
                    _mainView.FillCalendar(CalendarLists);
                }
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void LoadTimesList()
        {
            try
            {
                TimesList = _xrm.GetTimesList();

                if (TimesList != null)
                {
                    _mainView.FillTimes(TimesList);
                }
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        private void GetUsers(object sender, EventArgs e)
        {
            try
            {
                SystemUsers = _xrm.GetSystemUsers();

                if (SystemUsers != null)
                {
                    _mainView.SetUserList(SystemUsers);
                }
            }
            catch (Exception ex)
            {
                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);
            }
        }

        #region Connection

        private void ManagerStepChanged(object sender, EventArgs e)
        {
            _mainView.SetConnectionStatus(((StepChangedEventArgs)e).CurrentStep);
        }

        private void ManagerConnectionFailed(object sender, EventArgs e)
        {
            _mainView.SetConnectionStatus("Error: " + ((ConnectionFailedEventArgs)e).FailureReason);

            _xrm.ConnectionStatus(e);

            _traceService.WriteInfo("Error: " + ((ConnectionFailedEventArgs)e).FailureReason);
        }

        private void ManagerConnectionSucceed(object sender, EventArgs e)
        {
            try
            {
                _xrm.ConnectionStatus(e);
                _traceService.WriteInfo("Connected to " + ((ConnectionSucceedEventArgs)e).ConnectionDetail.ConnectionName);
                new Thread(SetDefaultValues).Start();
            }
            catch (Exception ex)
            {
                _messageService.ShowError(ex.Message);
                _traceService.WriteError(ex);

                throw new Exception(ex.Message, ex);
            }
        }

        #endregion Connection
    }
}